import os
import json
import time
import logging
from datetime import datetime
from mqttRev import SimpleMQTT

# ============ MQTT 配置 ============
RECV_TOPIC = "/iios/coco/mqtt-send/session/04f5c05f-db68-4ec4-9368-ed0ef9c60dda/msg"
SAVE_ROOT = "data_log"

# ============ 日志系统 ============
os.makedirs("logs", exist_ok=True)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
log_file = os.path.join("logs", f"mqtt_data_logger_{timestamp}.log")

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    handlers=[
        logging.FileHandler(log_file, encoding="utf-8"),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger("mqtt_data_logger")

# ============ 初始化 MQTT ============
mqtt_client = SimpleMQTT(
    host="192.168.6.7",
    port=2771,
    username="edge8563",
    password="XnZtSd1WlvF7Qt2E"
)

# ============ 保存函数 ============
def save_json_message(msg_data):
    """保存 JSON 数据到 data_log/日期/时分秒.json"""
    try:
        now = datetime.now()
        date_dir = os.path.join(SAVE_ROOT, now.strftime("%Y%m%d"))
        os.makedirs(date_dir, exist_ok=True)

        filename = os.path.join(date_dir, now.strftime("%H_%M_%S") + ".json")

        # 写入文件
        with open(filename, "w", encoding="utf-8") as f:
            json.dump(msg_data, f, ensure_ascii=False, indent=2)

        logger.info(f"💾 已保存到 {filename}")

    except Exception as e:
        logger.error(f"❌ 保存文件失败: {e}", exc_info=True)


# ============ 消息回调 ============
def on_message(topic, payload):
    try:
        logger.info(f"📩 收到 MQTT 消息 (前100字符): {payload[:10]}...")
        msg = json.loads(payload)

        # 如果是数组，只取第一个字典
        if isinstance(msg, list) and len(msg) > 0:
            msg_data = msg[0]
        else:
            msg_data = msg

        save_json_message(msg_data)

    except json.JSONDecodeError as e:
        logger.warning(f"⚠️ JSON 解析错误: {e}")
    except Exception as e:
        logger.error(f"❌ 消息处理异常: {e}", exc_info=True)


# ============ 主函数 ============
def main():
    mqtt_client.wait_connected(timeout=5)
    mqtt_client.subscribe(RECV_TOPIC, on_message)
    logger.info("🚀 MQTT 数据采集器已启动，等待数据中...")

    try:
        while True:
            time.sleep(0.5)
    except KeyboardInterrupt:
        mqtt_client.stop()
        logger.info("🛑 程序已结束。")


if __name__ == "__main__":
    main()
